#!/usr/bin/env python
# -*- coding:utf-8 -*-

import math

from app import db
from controller.collectionInfoController import CollectionInfoController
from models.collectionInfoModel import CollectionInfo
from models.passageInfoModel import PassageInfo
from utils import commons
from utils.response_code import RET, error_map_EN
from utils.loggings import loggings
import time
import re
from utils.validate_operate import verify_operator_object
from controller.userInfoController import UserInfoController


class CollectionInfoService(CollectionInfoController):
    @classmethod
    def joint_query(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('AutoID'):
                filter_list.append(cls.AutoID == kwargs.get('AutoID'))
            if kwargs.get('CUserID'):
                filter_list.append(cls.CUserID == kwargs.get('CUserID'))
            if kwargs.get('PassageID'):
                filter_list.append(cls.PassageID == kwargs.get('PassageID'))
            if kwargs.get('IsDelete'):
                filter_list.append(cls.IsDelete == kwargs.get('IsDelete'))
            if kwargs.get('CreateTime'):
                filter_list.append(cls.CreateTime == kwargs.get('CreateTime'))

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))

            collectionInfo_info = db.session.query(CollectionInfo.AutoID, CollectionInfo.CUserID,
                                                   CollectionInfo.PassageID, CollectionInfo.IsDelete,
                                                   CollectionInfo.CreateTime).filter(*filter_list)

            count = collectionInfo_info.count()
            pages = math.ceil(count / size)
            collectionInfo_info = collectionInfo_info.limit(size).offset((page - 1) * size).all()

            if not collectionInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}

            # 处理返回的数据
            results = commons.query_to_dict(collectionInfo_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages,
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    @classmethod
    def collect(cls, **kwargs):
        try:

            query_data = {'CUserID': kwargs.get('CUserID'), 'PassageID': kwargs.get('PassageID')}
            collectInfo = cls.get(**query_data)
            if collectInfo.get('code') == RET.OK:
                print(collectInfo)
                return {'code': RET.DATAEXIST, 'message': error_map_EN[RET.DATAEXIST],
                        'error': 'the user had collected yet'}

            # 二次查询减少数据冗余
            filter_list = [cls.IsDelete == 1, cls.CUserID == kwargs.get('CUserID'),
                           cls.PassageID == kwargs.get('PassageID')]
            reback_data = db.session.query(cls).filter(*filter_list)
            reback_data = reback_data.all()
            if reback_data:
                reback_data = commons.query_to_dict(reback_data)
                reback_data = {
                    'AutoID': reback_data[0].get('AutoID'),
                    'IsDelete': 0
                }

                cls.update(**reback_data)
                return {'code': RET.OK, 'message': error_map_EN[RET.OK],
                        'data': 'reback collect successfully'}
            results = cls.add(**kwargs)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK],
                    'data': results.get('data')}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()


    @classmethod
    @verify_operator_object([99, ], UserInfoController)
    def getcollectinfo(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('UserID'):
                filter_list.append(cls.CUserID == kwargs.get('UserID'))

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))

            collectionInfo_info = db.session.query(CollectionInfo.AutoID.label('CollectAutoID'), CollectionInfo.CUserID,
                                                   CollectionInfo.PassageID, CollectionInfo.IsDelete,
                                                   CollectionInfo.CreateTime, PassageInfo.PostTitle,
                                                   PassageInfo.PostAuthorID, PassageInfo.UpVoteNum, PassageInfo.LookNUM,
                                                   PassageInfo.CommentNum, PassageInfo.DeptType, PassageInfo.PostType,
                                                   PassageInfo.PostStatus,PassageInfo.PostContent).join(PassageInfo,
                                                                                PassageInfo.AutoID == CollectionInfo.PassageID).filter(
                *filter_list).order_by(cls.CreateTime.desc())

            count = collectionInfo_info.count()
            pages = math.ceil(count / size)
            collectionInfo_info = collectionInfo_info.limit(size).offset((page - 1) * size).all()

            if not collectionInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}

            # 处理返回的数据
            results = commons.query_to_dict(collectionInfo_info)
            for i in range(len(results)):
                img = re.search(r'(?<=(<img src=[\',"])).*?(?=([\',"]))', results[i]['PostContent'])
                if(img):
                    results[i]['img'] = img.group().replace("&amp", "&").replace("&;", "&")
                else:
                    results[i]['img'] = ''
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages,
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()
